<template>
  <el-dialog v-model="visible" title="新增备件" width="80%">
    <el-divider content-position="left">备件列表</el-divider>

    <div class="spare-table">
      <div class="table-header">
        <div class="col code">备件编码</div>
        <div class="col name">备件名称</div>
        <div class="col amount">金额</div>
        <div class="col info">厂商规格信息</div>
        <div class="col ops">操作</div>
      </div>

      <div v-for="(s, i) in spares" :key="s.uid" class="table-row">
        <div class="col code">
          <el-input v-model="s.code" placeholder="请输入编码" />
        </div>
        <div class="col name">
          <el-input v-model="s.name" placeholder="请输入名称" />
        </div>
        <div class="col amount">
          <el-input-number v-model="s.amount" :min="0" />
        </div>

        <div class="col info">
          <el-button size="small" type="primary" @click="openSpareDialog(i)">
            编辑({{ s.spares.length }})
          </el-button>
        </div>

        <div class="col ops">
          <el-button link size="small" type="primary" @click="copyRow(i)">复制</el-button>
          <el-button link size="small" type="danger" @click="removeRow(i)">删除</el-button>
        </div>
      </div>

      <div class="add-btn">
        <el-button size="small" type="success" plain @click="addRow">＋ 新增一行</el-button>
      </div>
    </div>

    <!-- 子弹窗 -->
    <el-dialog
      v-model="spareDialog.visible"
      title="编辑备件信息"
      width="70%"
      append-to-body
    >
      <div class="sub-table">
        <div class="sub-header">
          <div class="col vendor">厂商</div>
          <div class="col spec">规格</div>
          <div class="col ops">操作</div>
        </div>

        <div
          class="sub-row"
          v-for="(sr, j) in spareDialog.spares"
          :key="sr.uid"
        >
          <div class="col vendor">
            <el-input v-model="sr.vendor" placeholder="请输入厂商" />
          </div>
          <div class="col spec">
            <el-input v-model="sr.spec" placeholder="请输入规格" />
          </div>
          <div class="col ops">
            <el-button link size="small" @click="copySpare(j)">复制</el-button>
            <el-button link size="small" type="danger" @click="removeSpare(j)">删除</el-button>
          </div>
        </div>

        <div class="add-btn">
          <el-button size="small" type="success" plain @click="addSpare">＋ 新增一行</el-button>
        </div>
      </div>

      <template #footer>
        <el-button @click="spareDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveSpares">确定</el-button>
      </template>
    </el-dialog>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="confirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";

const visible = ref(false);
const spares = reactive([]);

function addRow() {
  spares.push({
    uid: Math.random().toString(36).slice(2),
    code: "",
    name: "",
    amount: 0,
    spares: [], // 子项（厂商/规格）
  });
}
function copyRow(i) {
  const newRow = JSON.parse(JSON.stringify(spares[i]));
  newRow.uid = Math.random().toString(36).slice(2);
  spares.splice(i + 1, 0, newRow);
}
function removeRow(i) {
  spares.splice(i, 1);
}

// 子弹窗逻辑
const spareDialog = reactive({
  visible: false,
  index: null,
  spares: [],
});

function openSpareDialog(i) {
  spareDialog.index = i;
  spareDialog.spares = JSON.parse(JSON.stringify(spares[i].spares || []));
  if (!spareDialog.spares.length) addSpare();
  spareDialog.visible = true;
}
function addSpare() {
  spareDialog.spares.push({
    uid: Math.random().toString(36).slice(2),
    vendor: "",
    spec: "",
  });
}
function copySpare(j) {
  const newRow = JSON.parse(JSON.stringify(spareDialog.spares[j]));
  newRow.uid = Math.random().toString(36).slice(2);
  spareDialog.spares.splice(j + 1, 0, newRow);
}
function removeSpare(j) {
  spareDialog.spares.splice(j, 1);
}
function saveSpares() {
  spares[spareDialog.index].spares = JSON.parse(JSON.stringify(spareDialog.spares));
  spareDialog.visible = false;
}

// ✅ 改：只 emit 数据，不提交
const emit = defineEmits(["confirm"]);

function confirm() {
  if (!spares.length) return ElMessage.error("请至少添加一个备件");

  const data = spares.map(({ code, name, amount, spares: subs }) => ({
    code,
    name,
    amount,
    spareDetails: subs.map((s) => ({
      vendor: s.vendor,
      spec: s.spec,
    })),
  }));

  emit("confirm", data); // ✅ 父组件接收
  visible.value = false;
}

const open = () => {
  visible.value = true;
  spares.splice(0);
  addRow();
};
defineExpose({ open });
</script>

<style scoped>
.spare-table,
.sub-table {
  border: 1px solid #ebeef5;
  border-radius: 8px;
}
.table-header,
.table-row {
  display: grid;
  align-items: center;
  border-bottom: 1px solid #ebeef5;
  padding: 6px 8px;
  grid-template-columns: 20% 20% 15% 20% 25%;
}
.table-header {
  background: #f5f7fa;
  font-weight: 500;
}
.sub-header,
.sub-row {
  display: grid;
  align-items: center;
  border-bottom: 1px solid #ebeef5;
  padding: 6px 8px;
  grid-template-columns: 45% 45% 10%;
}
.sub-header {
  background: #f5f7fa;
  font-weight: 500;
}
.col {
  padding: 4px;
}
.col.ops {
  text-align: center;
}
.add-btn {
  text-align: right;
  padding: 8px;
}
</style>
